package com.kolon.business.mngr.client.controller;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import com.kolon.business.mngr.client.dao.ClientDao;
import com.kolon.framework.constant.Constant;
import com.kolon.framework.file.DefaultFileRenamePolicy;
import com.kolon.framework.file.FileUtil;
import com.kolon.framework.file.UploadedFile;
import com.kolon.framework.interfaces.SimpleController;
import com.kolon.framework.util.ComUtil;
import com.kolon.framework.util.MsgUtil;

@Controller("com.kolon.business.mngr.client.controller.ClientUpgradeController")
public class ClientUpgradeController implements SimpleController {
	
	@Resource(name="com.kolon.business.mngr.client.dao.ClientDaoImpl")
	private ClientDao clientDao;
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@RequestMapping(value="/business/mngr/client/clientUpgrade.do")
	public ModelAndView controller(HttpServletRequest request,
		HttpServletResponse response) throws Exception {
		
		ModelAndView modelAndView = new ModelAndView();
		MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
		Map<String, String> map = new HashMap<String, String>();
		List<UploadedFile> fileList = new ArrayList<UploadedFile>();
		// 파라미터frfTp
		String frfTp = ComUtil.nullChk(request.getParameter("frfTp"));
		String frfVer = multiRequest.getParameter("frfVer");
		map.put("frfTp", frfTp);
		map.put("appCntDesc", ComUtil.nullChk(multiRequest.getParameter("appCntDesc")));
		map.put("frfVer", frfVer);
		// 서비스 정보 조회
		Map cntMap = clientDao.getMap(map);
		if (cntMap == null)
			return new ModelAndView("redirect:/business/mngr/client/clientUpgradeForm.do");
		// 앱 파일 저장 경로
		String appFilePath = MsgUtil.getMessage("app.file.path");
		appFilePath = appFilePath + frfTp.toLowerCase() + File.separator + Constant.APP_CNT_NM + File.separator;
		// 중복 체크
		if (!frfVer.equals(cntMap.get("FRF_VER"))) {
			if (clientDao.getAppHstyCnt(map) > 0)
				return new ModelAndView("redirect:/business/mngr/client/clientUpgradeForm.do");
		}
		// STEP START
		try {
			// STEP 01. 업그레이드 시 기존 앱 파일을 버전 폴더로
			for (int i=1; i<=3; i++) {
				FileUtil.fileCopy(appFilePath  + cntMap.get("FILE_S_NM_"+i), 
					appFilePath + cntMap.get("FRF_VER") + File.separator, ComUtil.oTos(cntMap.get("FILE_S_NM_"+i)));
			}
			// STEP 02. 앱 시퀀스 값 조회
			cntMap.put("APP_HSTY_CNT_NO", ComUtil.oTos(clientDao.getHstyCntMax().get("APP_HSTY_CNT_NO")));
			// STEP 03. 앱 히스토리 등록
			clientDao.insertHstyCntInfo(cntMap);
			// STEP 04. 앱 파일 업로드
			for (int i=1; i<=3; i++) {
				MultipartFile mFile = multiRequest.getFile("appFile"+i);
				// 업로드 시 기존 파일 삭제
				if (!"".equals(mFile.getOriginalFilename()))
					FileUtil.delFile(appFilePath + cntMap.get("FILE_S_NM_"+i));
				UploadedFile uploadedFile = FileUtil.fileUpload(mFile, 
						appFilePath, new DefaultFileRenamePolicy());
				map.put("fileRNm"+i, uploadedFile.getFileRealName());
				map.put("fileSNm"+i, uploadedFile.getFileName());
				map.put("fileTp"+i, uploadedFile.getExtension());
				map.put("fileSize"+i, String.valueOf(uploadedFile.getSize()));
				fileList.add(uploadedFile);
			}
			// STEP 05. 서비스 정보 수정
			clientDao.upgrade(map);
			modelAndView.addObject("chk", "Y");
		} catch (Exception e) {
			// 등록된 히스토리 삭제
			map.put("appHstyCntNo", ComUtil.oTos(cntMap.get("APP_HSTY_CNT_NO")));
			clientDao.deleteHstyCntInfo(map);
			// 예외 발생 시 업로드 된 파일을 삭제
			FileUtil.dirDelete(new File(appFilePath + cntMap.get("FRF_VER") + File.separator));
			for (int i=0, size=fileList.size(); i<size; i++)
				FileUtil.delFile(appFilePath + fileList.get(i).getFileName());
			modelAndView.addObject("chk", "N");
		}
		// 리턴
		modelAndView.setViewName("redirect:/business/mngr/client/clientUpgradeForm.do");
		modelAndView.addObject("frfTp", frfTp);
		modelAndView.addObject("pop", "Y");
		return modelAndView;
	}
}
